using System;
using System.Diagnostics;
using System.Drawing;
using SdlDotNet.Core;
using SdlDotNet.Graphics;
using SdlDotNet.Graphics.Sprites;

namespace NielsRask.Mucus
{
	public class Form : Control
	{
		private ControlCollection controls;
		private Surface screen;
		private bool showFps = false;

		public bool ShowFps
		{
			get { return showFps; }
			set { showFps = value; }
		}

		public Form(Surface surface) :this()
		{
			this.screen = surface;
			this.size = surface.Size;
		}

		public Form()
		{
			controls = new ControlCollection(this);
			Events.Tick += Events_Tick;
			Events.Quit += Events_Quit;
		}

        public override bool Click(SdlDotNet.Input.MouseButtonEventArgs e)
        {
            foreach (Control ctrl in controls)
            {
                if (ctrl.IsPointWithinControl(e.Position))
                {
                    ctrl.Click(e);
                    return true;
                }
            }

            return false;
        }

		//public event 

		public Form(Size size) : this()
		{
			this.size = size;
			screen = new Surface( size );
		}

		public ControlCollection Controls
		{
			get { return controls; }
			set { controls = value; }
		}

		void Events_Tick( object sender, TickEventArgs e )
		{
			Render(null);
		}

		void Events_Quit( object sender, QuitEventArgs e )
		{
			Trace.WriteLine( "closing sdlform" );
			Events.CloseVideo();
			Events.Close();

			if (OnClose != null)
				OnClose(null, null);

			Events.QuitApplication();
		}
		public event EventHandler OnClose;//(object sender, System.EventArgs e);


		public override void Render( Surface unused )
		{
			screen.Fill( new Rectangle( new Point( 0, 0 ), screen.Size ), Color.FromArgb( 0, 0, 0 ) );
			
			for ( int i = 0; i < controls.Count; i++ )
				controls[i].Render( screen );

			if ( showFps )
				RenderFps();

			screen.Update();
		}

		private void RenderFps()
		{
			TextSprite tsp = new TextSprite( "FPS: " + Events.Fps, new SdlDotNet.Graphics.Font( @"c:\windows\fonts\arial.ttf", 12 ) );
			screen.Blit( tsp.Surface, new Point( 0, 0 ) );
		}


		public void Show()
		{
			screen = Video.SetVideoMode( size.Width, size.Height, 16, true, false, false );
			screen.Fill( new Rectangle( new Point( 0, 0 ), screen.Size ), Color.FromArgb( 0, 0, 0 ) );
			Events.Run();
		}
	}
}
